package byx.container.annotation.extension.impl;

import byx.container.annotation.annotation.AnnotatedBy;
import byx.container.annotation.extension.core.ParameterHandler;
import byx.container.annotation.extension.core.ParameterInfo;
import byx.container.core.Container;
import byx.container.core.ObjectFactory;
import byx.container.core.Predicates;
import byx.container.core.utils.CastUtils;

import java.lang.annotation.Annotation;
import java.util.Collection;

import static byx.container.core.ObjectFactories.allFromContainer;

/**
 * AnnotatedBy注解参数处理器
 */
public class AnnotatedByParameterHandler implements ParameterHandler {
    @Override
    public boolean support(ParameterInfo param) {
        return param.getAnnotationMetadata().isAnnotationPresent(AnnotatedBy.class)
                && Collection.class.isAssignableFrom(param.getParameterType());
    }

    @Override
    public ObjectFactory<?> handle(ParameterInfo param, Container container) {
        Class<?> collectionType = param.getParameterType();
        Class<? extends Annotation> annotationType = param.getAnnotationMetadata().getAnnotation(AnnotatedBy.class).value();
        return allFromContainer(container, Predicates.annotatedBy(annotationType))
                .map(CastUtils.cast(CollectionConverter.converter(collectionType)));
    }
}
